<template>
  <div class="app-container">
    <el-form :model="searchForm" label-width="80px" @keyup.enter.native="search()">
      <el-row>
        <el-col class="other">
          <el-form-item label="外联单位" size="small">
            <el-input v-model="searchForm.companyTitle"></el-input>
          </el-form-item>
        </el-col>
        <el-col class="address">
          <el-form-item label="地区搜索" size="small">
            <el-select v-model="searchForm.provinceId" placeholder="请选择省份" @change="provinceChange">
              <el-option value="" label="全部"></el-option>
              <el-option
                v-for="(item,key) in pca[86]"
                :key="key"
                :label="item"
                :value="key">
              </el-option>
            </el-select>
            <el-select size="small" v-model="searchForm.cityId" placeholder="请选择城市">
              <el-option value="" label="全部"></el-option>
              <el-option
                v-for="(item,key) in pca[searchForm.provinceId]"
                :key="key"
                :label="item"
                :value="key">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col class="searchBtn">
          <el-form-item size="small">
            <el-button type="primary" icon="el-icon-search" @click="search()">搜索</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div class="table-btn">
      <el-button type="primary" size="small" icon="el-icon-plus" @click="addTeam()">添加</el-button>
      <el-dialog :title="dialogTitle" :visible.sync="outerVisible" width="950px">
        <el-form ref="teamRow" :rules="rules" :model="teamRow" label-width="110px">
          <el-form-item prop="projectName" label="项目名称" size="small">
            <el-input type="text" v-model="teamRow.projectName"></el-input>
          </el-form-item>
          <el-form-item prop="companyTitle" label="外联单位" size="small">
            <el-autocomplete
              v-model="teamRow.companyTitle"
              :fetch-suggestions="querySearchOutitemsCompany"
              @select="handleSelectOutitemsCompany"
              placeholder="请输入内容"
            >
            </el-autocomplete>
          </el-form-item>
          <el-form-item prop="addressId" label="项目地区" size="small">
            <area-cascader v-model="teamRow.addressId" v-if="isAddress" placeholder="请选择省市" :data="pca"
                           @change="addressChange()"></area-cascader>
          </el-form-item>
          <el-form-item prop="partyA" label="甲方单位" size="small">
            <el-input type="text" v-model="teamRow.partyA"></el-input>
          </el-form-item>
          <el-form-item prop="contractCode" label="合同编号" size="small">
            <el-input type="text" v-model="teamRow.contractCode"></el-input>
          </el-form-item>
          <el-form-item prop="contractAmount" label="合同金额" size="small">
            <el-input type="number" v-model.number="teamRow.contractAmount">
              <span slot="suffix">万元</span>
            </el-input>
          </el-form-item>
          <el-form-item prop="signer" label="签订人" size="small">
            <el-input type="text" v-model="teamRow.signer"></el-input>
          </el-form-item>
          <el-form-item prop="singTime" label="签订时间" size="small">
            <el-date-picker
              v-model="teamRow.singTime"
              type="date"
              value-format="yyyy-MM-dd"
              placeholder="选择日期">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="负责人" size="small">
            <el-input type="text" v-model="teamRow.contactPerson"></el-input>
          </el-form-item>
          <el-form-item prop="contact" label="联系方式" size="small">
            <el-input type="text" v-model="teamRow.contact"></el-input>
          </el-form-item>
          <el-form-item label="阶段进度" size="small">
            <el-button type="primary" icon="el-icon-plus" @click="addpp()"></el-button>
          </el-form-item>
          <el-row v-for="(item,index) in pp">
            <el-col class="other">
              <el-form-item label="百分比" size="small">
                <el-input type="number" v-model="item.percentage" @input="percentageChange(item,index)">
                  <span slot="suffix">%</span>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col class="other">
              <el-form-item label="金额" size="small">
                <el-input type="number" v-model="item.price">
                  <span slot="suffix">万元</span>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col class="other">
              <el-form-item label="节点" size="small">
                <el-input type="text" v-model="item.node"></el-input>
              </el-form-item>
            </el-col>
            <el-col class="searchBtn">
              <el-form-item size="small">
                <el-button type="danger" size="small" icon="el-icon-minus" @click="delpp(index)"></el-button>
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="有无项目子项目" size="small">
            <el-switch
              v-model="teamRow.isProject"
              active-color="#13ce66"
              inactive-color="#ff4949"
              :active-value=1
              :inactive-value=0
            >
            </el-switch>
          </el-form-item>
          <el-form-item prop="balance" v-if="teamRow.isProject" label="结算差额" size="small">
            <el-input type="number" v-model="teamRow.balance">
              <span slot="suffix">万元</span>
            </el-input>
          </el-form-item>
          <el-form-item prop="isAdd" v-if="teamRow.isProject" label="形式" size="small">
            <el-radio-group v-model="teamRow.isAdd">
              <el-radio :label="1">增</el-radio>
              <el-radio :label="0">减</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="子备注" v-if="teamRow.isProject" size="small">
            <el-input type="textarea" v-model="teamRow.childRemark"></el-input>
          </el-form-item>
          <el-form-item label="备注说明" size="small">
            <el-input type="textarea" v-model="teamRow.remark"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="warning" size="small"  @click="submitForm('teamRow')" v-no-more-click>确定</el-button>
          <el-button size="small" @click="outerVisible = false;isAddress = false">取消</el-button>
        </div>
      </el-dialog>
      <!--<el-button size="small" icon="el-icon-upload2">导出</el-button>-->
    </div>
    <my-table
      :data="tableData"
      :col-configs="colConfigs"
      v-loading="listLoading"
      :page-num="pageNum"
      :page-size="pageSize"
    >
      <el-table-column
        slot="opt"
        fixed="right"
        label="操作"
        width="200">
        <template slot-scope="scope">
          <el-button
            @click.native.prevent="editTeam(scope.row.projectId)"
            type="text"
            size="small">
            修改
          </el-button>
          <el-popover
            placement="top"
            width="160"
            :ref="`popover-${scope.$index}`"
          >
            <p>确定删除这条数据吗?</p>
            <div style="text-align: right; schedule: 0">
              <el-button size="mini" type="text" @click="$refs[`popover-${scope.$index}`].doClose()">取消</el-button>
              <el-button type="primary" size="mini" @click.native.prevent="deleteRow(scope)">确定</el-button>
            </div>
            <el-button type="text" size="small" slot="reference" v-popover:popover-${scope.$index}>删除</el-button>
          </el-popover>
        </template>
      </el-table-column>
    </my-table>
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="pageNum"
      :page-sizes="[10, 20, 30, 40]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total">
    </el-pagination>
  </div>
</template>

<script>
  import {
    deleteOutitems,
    getOutitemsList,
    insertOutitems,
    selectOutitems,
    selectOutitemsCompany,
    selectProjects,
    updateOutitems
  } from '@/api/outitems'
  import myTable from '@/components/myTable'

  import { AreaSelect } from 'vue-area-linkage'
  import { pca } from 'area-data'
  import { formatDate } from '@/utils/index'
  import { isvalidPhone } from '@/utils/validate'

  const address = {
    props: ['colConfig'],
    data() {
      return {
        pca: pca
      }
    },
    template: `
  <el-table-column :label="colConfig.label" :width="colConfig.width">
      <span slot-scope="scope">
        {{ pca[86][scope.row.provinceId] + pca[scope.row.provinceId][scope.row.cityId]}}
      </span>
  </el-table-column>
  `
  }

  const isProject = function(row, column) {
    return row.isProject === 1 ? '有' : '无'
  }

  const isAdd = function(row, column) {
    return row.isAdd === 1 ? '增' : '减'
  }

  export default {
    components: {
      myTable,
      AreaSelect
    },
    data() {
      const validPhone = (rule, value, callback) => {
        if (!value) {
          callback()
        } else if (!isvalidPhone(value)) {
          callback(new Error('请输入正确的11位手机号码'))
        } else {
          callback()
        }
      }
      return {
        colConfigs: [
          { prop: 'projectName', label: '项目名称', width: '150', fixed: true },
          { prop: 'pca', label: '地区', width: '150', component: address },
          { prop: 'companyTitle', label: '外联单位', width: '150' },
          { prop: 'contractCode', label: '合同编号', width: '150' },
          { prop: 'partyA', label: '甲方单位', width: '150' },
          { prop: 'signer', label: '签订人', width: '150' },
          { prop: 'isProject', label: '有无项目子项目', width: '150', formatter: isProject },
          { prop: 'balance', label: '结算差额(万元)', width: '150' },
          { prop: 'isAdd', label: '形式', width: '150', formatter: isAdd },
          { prop: 'childRemark', label: '子备注', width: '150' },
          { slot: 'opt' }
        ],
        searchForm: {
          provinceId: '',
          cityId: ''
        },
        searchFormList: {},
        costTypes: [],
        typeNames: [],
        listLoading: true,
        scheduleLoading: true,
        dialogTitle: '新增外联项目表',
        scheduleTitle: '分公司筹建制度日志信息管理',
        scheduleType: 1,
        dialogType: 0,
        teamRow: {
          isProject: 0,
          contact: ''
        },
        teamRowClear: {},
        schedule: {},
        scheduleClear: {},
        tableData: [],
        scheduleData: [],
        pageNum: 1,
        pageSize: 10,
        total: 0,
        outerVisible: false,
        scheduleVisible: false,
        isAddress: true, // 地区新增 修改 摧毁 生成组件
        pca: pca,
        rules: {
          projectName: [
            { required: true, message: '请输入项目名称', trigger: 'change' }
          ],
          companyTitle: [
            { required: true, message: '请输入外联单位', trigger: 'change' }
          ],
          addressId: [
            { required: true, message: '请选择地址', trigger: 'change' }
          ],
          contractCode: [
            { required: true, message: '合同编号', trigger: 'change' }
          ],
          contractAmount: [
            { required: true, message: '请输入合同金额', trigger: 'change' }
          ],
          partyA: [
            { required: true, message: '请输入甲方单位', trigger: 'change' }
          ],
          signer: [
            { required: true, message: '请输入签订人', trigger: 'change' }
          ],
          singTime: [
            { required: true, message: '请选择签订日期', trigger: 'change' }
          ],
          balance: [
            { required: true, message: '请输入结算差额', trigger: 'change' }
          ],
          isAdd: [
            { required: true, message: '请选择形式', trigger: 'change' }
          ],
          contact: [
            { required: false, trigger: 'blur', validator: validPhone }
          ]
        },
        visible: false,
        pp: []
      }
    },
    created() {
      this.teamRowClear = JSON.parse(JSON.stringify(this.teamRow))
      this.fetchData()
    },
    methods: {
      fetchData() {
        this.searchFormList.pageNum = this.pageNum
        this.searchFormList.pageSize = this.pageSize
        this.listLoading = true
        getOutitemsList(this.searchFormList).then(response => {
          this.tableData = response.responseBody.list
          this.total = response.responseBody.total
          console.log(this.tableData)
          this.listLoading = false
        })
      },
      provinceChange() {
        this.searchForm.cityId = ''
      },
      search() {
        this.pageNum = 1
        this.searchFormList = JSON.parse(JSON.stringify(this.searchForm))
        this.fetchData()
      },
      addTeam() {
        this.outerVisible = true
        this.isAddress = true
        this.dialogTitle = '新增外联项目表'
        this.teamRow = JSON.parse(JSON.stringify(this.teamRowClear))
        if (this.$refs['teamRow']) {
          this.$refs['teamRow'].resetFields()
        }
        this.pp = []
        this.dialogType = 1
        if (this.$refs.payCertificate) {
          this.$refs.payCertificate.value = ''
        }
      },
      editTeam(projectId) {
        if (this.$refs['teamRow']) {
          this.$refs['teamRow'].resetFields()
        }
        this.outerVisible = true
        this.isAddress = true
        this.dialogTitle = '修改外联项目表'
        this.dialogType = 0
        if (this.$refs.payCertificate) {
          this.$refs.payCertificate.value = ''
        }
        this.teamRow = JSON.parse(JSON.stringify(this.teamRowClear))
        this.pp = []
        const params = {
          projectId: projectId
        }
        selectOutitems(params).then(response => {
          this.teamRow = response.responseBody
          this.$set(this.teamRow, 'singTime', formatDate(new Date(this.teamRow.signDate), 'yyyy-MM-dd'))
          this.teamRow.addressId = [this.teamRow.provinceId.toString(), this.teamRow.cityId.toString()]
          this.teamRow.pp.forEach(value => {
            this.pp.push({
              price: value.price,
              percentage: value.percentage,
              node: value.node
            })
          })
        })
      },
      submitForm(formName) {
        const params = {
          projectName: this.teamRow.projectName,
          outCompanyId: this.teamRow.outCompanyId,
          provinceId: this.teamRow.provinceId,
          cityId: this.teamRow.cityId,
          contractCode: this.teamRow.contractCode,
          contractAmount: this.teamRow.contractAmount,
          partyA: this.teamRow.partyA,
          signer: this.teamRow.signer,
          singTime: this.teamRow.singTime,
          contactPerson: this.teamRow.contactPerson ? this.teamRow.contactPerson : '',
          contact: this.teamRow.contact ? this.teamRow.contact : '',
          remark: this.teamRow.remark ? this.teamRow.remark : '',
          isProject: this.teamRow.isProject,
          pp: this.pp
        }
        if (this.teamRow.isProject) {
          params.balance = this.teamRow.balance
          params.isAdd = this.teamRow.isAdd
          params.childRemark = this.teamRow.childRemark ? this.teamRow.childRemark : ''
        }
        if (!this.dialogType) {
          params.projectId = this.teamRow.projectId
        }
        if (this.teamRow.outCompanyId) {
          this.$refs[formName].validate((valid) => {
            if (valid) {
              if (this.dialogType) {
                insertOutitems(params).then(response => {
                  console.log(response)
                  this.outerVisible = false
                  this.isAddress = false
                  this.fetchData()
                })
              } else {
                updateOutitems(params).then(response => {
                  console.log(response)
                  this.outerVisible = false
                  this.isAddress = false
                  this.fetchData()
                })
              }
            } else {
              console.log('error submit!!')
              return false
            }
          })
        } else {
          this.$message({
            message: '该外联单位不存在',
            type: 'warning'
          })
        }
      },
      deleteRow(scope) {
        this.$refs[`popover-${scope.$index}`].doClose()
        const params = {
          projectId: scope.row.projectId,
          isDel: 1
        }
        deleteOutitems(params).then(response => {
          this.fetchData()
        })
      },
      handleSizeChange(val) {
        this.pageSize = val
        this.fetchData()
      },
      handleCurrentChange(val) {
        this.pageNum = val
        this.fetchData()
      },
      addressChange() {
        this.teamRow.provinceId = parseInt(this.teamRow.addressId[0])
        this.teamRow.cityId = parseInt(this.teamRow.addressId[1])
        this.teamRow.address = this.pca[86][this.teamRow.addressId[0]] + this.pca[this.teamRow.addressId[0]][this.teamRow.addressId[1]]
      },
      querySearchProject(queryString, callback) {
        // queryString 为在框中输入的值
        // callback 回调函数,将处理好的数据推回
        if (queryString) {
          const params = {
            projectName: queryString
          }
          selectProjects(params).then(response => {
            for (const i of response.responseBody) {
              i.value = i.projectName
            }
            let projectList = response.responseBody
            if (projectList.length === 0) {
              projectList = [{ value: '暂无数据' }]
            }
            callback(projectList)
          })
        } else {
          callback([])
        }
      },
      handleSelectProject(item) {
        this.$set(this.teamRow, 'projectId', item.projectId)
      },
      querySearchOutitemsCompany(queryString, callback) {
        // queryString 为在框中输入的值
        // callback 回调函数,将处理好的数据推回
        delete this.teamRow.outCompanyId
        if (queryString) {
          const params = {
            projectName: queryString
          }
          selectOutitemsCompany(params).then(response => {
            for (const i of response.responseBody) {
              i.value = i.companyTitle
            }
            let projectList = response.responseBody
            if (projectList.length === 0) {
              projectList = [{ value: '暂无数据' }]
            }
            callback(projectList)
          })
        } else {
          callback([])
        }
      },
      handleSelectOutitemsCompany(item) {
        this.teamRow.outCompanyId = item.companyId
      },
      addpp() {
        this.pp.push({
          price: 0,
          percentage: 0,
          node: ''
        })
      },
      delpp(index) {
        this.pp.splice(index, 1)
      },
      percentageChange(item, index) {
        const price = item.percentage / 100 * this.teamRow.contractAmount || 0
        this.pp[index].price = Math.round(price * 100) / 100
      }
    },
    mounted() {
      console.log(this.pca)
    },
    watch: {
      'teamRow.contractAmount': {
        handler(newValue, oldValue) {
          this.pp.forEach(value => {
            value.price = Math.round(value.percentage / 100 * newValue * 100) / 100
          })
        },
        immediate: true
      }
    }
  }
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
  .app-container {
    .el-pagination {
      schedule-top: 20px;
    }
    .table-btn {
      margin-bottom: 10px;
      & > button {
        schedule: 0 20px;
      }
      .el-dialog {
        textarea {
          schedule-top: 10px;
        }
        .el-checkbox {
          schedule-right: 20px;
        }
        .el-checkbox + .el-checkbox {
          schedule-left: 0;
        }
      }
    }
    .searchBtn {
      margin-left: 20px;
    }
  }

</style>


<style rel="stylesheet/scss" lang="scss">
  .el-input__icon {
    line-height: 100%;
  }

  .el-form-item__content {
    line-height: 33px;
  }

  .area-select .area-selected-trigger {
    padding: 0 10px;
  }

  /*.el-table__body tr.hover-row>td {
    background-color: #0000ff !important;
  }

  .el-table__body tr.current-row>td {
    background-color: #0000ff !important;
  }*/
</style>
